#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->ui->pushButton_start->setDisabled(true);
    this->ui->pushButton_stop->setDisabled(true);
    this->ui->pushButton_stopThread->setDisabled(true);

    connect(&aDiceThread, SIGNAL(started()), this, SLOT(diceThread_start()));
    connect(&aDiceThread, SIGNAL(finished()), this, SLOT(diceThread_stop()));
    connect(&aDiceThread, SIGNAL(newDiceValue(int,int)), this, SLOT(receive_diceThread_value(int,int)));

    this->setQLabelPicByPath(this->ui->label_pic, ":/images/images/d0.jpg");
}

MainWindow::~MainWindow()
{
    delete ui;
    aDiceThread.requestInterruption();
    aDiceThread.wait(5000);
}

void MainWindow::setQLabelPicByPath(QLabel *label, QString path)
{
    QPixmap pixMap;
    pixMap.load(path);
    label->setPixmap(pixMap);
}


void MainWindow::on_pushButton_startThread_clicked()
{
    this->aDiceThread.start();
    this->ui->pushButton_start->setDisabled(false);
    this->ui->pushButton_startThread->setDisabled(true);
    this->ui->pushButton_stopThread->setDisabled(false);

}

void MainWindow::on_pushButton_start_clicked()
{
    this->aDiceThread.startDice();
    this->ui->pushButton_start->setDisabled(true);
    this->ui->pushButton_stop->setDisabled(false);
}

void MainWindow::on_pushButton_stop_clicked()
{
    this->aDiceThread.pauseDice();
    this->ui->pushButton_stop->setDisabled(true);
    this->ui->pushButton_start->setDisabled(false);
}

void MainWindow::receive_diceThread_value(int seq, int v)
{
    qDebug()<<seq<<"-"<<v;
    QString info;
    info.sprintf("seq is %d, dice is %d", seq, v);
    this->ui->textEdit_info->append(info);

    this->setQLabelPicByPath(this->ui->label_pic, QString::asprintf(":/images/images/d%d.jpg", v + 1));
}

void MainWindow::diceThread_start()
{
    this->ui->label_threadStatus->setText("thread started");
}

void MainWindow::diceThread_stop()
{
    this->ui->label_threadStatus->setText("thread stop");

}

void MainWindow::on_pushButton_stopThread_clicked()
{
    this->aDiceThread.requestInterruption();
    this->ui->pushButton_startThread->setDisabled(false);
    this->ui->pushButton_stopThread->setDisabled(true);
}

void MainWindow::on_pushButton_clearText_clicked()
{
    this->ui->textEdit_info->clear();
}
